//
// Created by 朱宗辉 on 25-6-8.
//
#include <fuquOS/fat32.h>
#include<fuquOS/block.h>
#include <fuquOS/printk.h>


void fat32_init() {
    for (int i = 0; i < 4; i++) {
        PartitionEntry *part = &(mbr->partitions[i]);
        if (part->type == 0) continue;

        printk("Partition %d: type %x, start LBA %d, size %d MB\n",
               i, part->type, part->lba_start, part->sectors / 2048);

        if (part->type == 0x0B || part->type == 0x0C) {
            printk("Detected FAT32 at partition %d\n", i);

            static u8 fat32_buf[512] __attribute__((aligned(512)));
            read_disk(part->lba_start, (u16 *) fat32_buf);

            BPB_FAT32 *bpb = (BPB_FAT32 *) fat32_buf;
            printk("FAT32 Info:\n");
            printk("  OEM Name: %.8s\n", bpb->OEMName);
            printk("  Bytes per Sector: %u\n", bpb->bytesPerSector);
            printk("  Sectors per Cluster: %u\n", bpb->sectorsPerCluster);
            printk("  Reserved Sector Count: %u\n", bpb->reservedSectorCount);
            printk("  Number of FATs: %u\n", bpb->numFATs);
            printk("  FAT Size (sectors): %u\n", bpb->fatSize32);
            printk("  Root Cluster: %u\n", bpb->rootCluster);
            printk("  Total Sectors: %u\n", bpb->totalSectors32);
            printk("  Volume Label: %.11s\n", bpb->volumeLabel);
            printk("  FS Type: %.8s\n", bpb->fsType);
        }
    }
}


u32 cluster_to_lba(u32 cluster, BPB_FAT32 *bpb, u32 partition_start_lba) {
    u32 data_region_lba = partition_start_lba +
                          bpb->reservedSectorCount +
                          bpb->numFATs * bpb->fatSize32;
    return data_region_lba + (cluster - 2) * bpb->sectorsPerCluster;
}
